package com.owen.java.demo.quartz;

import com.owen.java.demo.quartz.job.JobA;
import com.owen.java.demo.quartz.job.JobB;
import com.owen.java.demo.quartz.job.JobC;
import com.owen.java.demo.quartz.listener.DependencyJobListener;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

public class QuartzTest2 {

    public static void main(String[] args) throws SchedulerException {
        Scheduler scheduler=StdSchedulerFactory.getDefaultScheduler();

        JobKey jobAKey = new JobKey("jobA", "group1");
        JobKey jobBKey = new JobKey("jobB", "group1");
        JobKey jobCKey = new JobKey("jobC", "group1");

        JobDetail jobA= JobBuilder.newJob()
                .ofType(JobA.class)
                .withIdentity(jobAKey)
                .storeDurably(true)
                .build();

        JobDetail jobB= JobBuilder.newJob()
                .ofType(JobB.class)
                .withIdentity(jobBKey)
                .storeDurably(true)
                .build();

        JobDetail jobC= JobBuilder.newJob()
                .ofType(JobC.class)
                .withIdentity(jobCKey)
                .storeDurably(true)
                .build();

        TriggerBuilder<SimpleTrigger> triggerBuilderA = TriggerBuilder.newTrigger()
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInSeconds(1))
                .startNow();
        TriggerBuilder<SimpleTrigger> triggerBuilderB = TriggerBuilder.newTrigger()
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInSeconds(1))
                .startNow();
        TriggerBuilder<SimpleTrigger> triggerBuilderC = TriggerBuilder.newTrigger()
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInSeconds(1))
                .startNow();

        // 初始化依赖关系
        DependencyJobListener listener = new DependencyJobListener();
        listener.addDependency(jobAKey, jobBKey);
        listener.addDependency(jobAKey, jobCKey);

        // 注册监听器
        scheduler.getListenerManager().addJobListener(listener);

        // 先将所有Job添加到调度器（不立即触发）
        scheduler.addJob(jobA, true); // true表示替换已存在的
//        scheduler.addJob(jobB, true);
//        scheduler.addJob(jobC, true);

        // 注意：不需要显式调度jobA，它会被监听器触发
//        scheduler.scheduleJob(jobA, triggerBuilderA.build());
        scheduler.scheduleJob(jobB, triggerBuilderB.build());
        scheduler.scheduleJob(jobC, triggerBuilderC.build());

        scheduler.start();
    }

}
